package megalopolis.editor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

public class MainFrame extends JFrame implements View, ActionListener {

	private Controller controller;

	private JMenuItem fileNew;

	private JMenuItem fileLoad;

	private JMenuItem fileExit;

	private JMenuItem fileSaveAs;

	public MainFrame(Controller controller) {
		super("Editor");

		this.controller = controller;

		createMainMenu();
		createUI();
	}

	private void createUI() {
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				controller.exit();
			}
		});
		setSize(500, 400);
		setLocationRelativeTo(null);
	}

	private void createMainMenu() {
		JMenuBar menuBar = new JMenuBar();

		JMenu file = new JMenu("File");
		menuBar.add(file);
		fileNew = new JMenuItem("New");
		fileNew.addActionListener(this);
		file.add(fileNew);
		fileLoad = new JMenuItem("Load");
		file.add(fileLoad);
		fileSaveAs = new JMenuItem("Save as");
		fileSaveAs.addActionListener(this);
		file.add(fileSaveAs);
		fileLoad.addActionListener(this);
		fileExit = new JMenuItem("Exit");
		fileExit.addActionListener(this);
		file.add(fileExit);

		setJMenuBar(menuBar);
	}

	public void actionPerformed(ActionEvent e) {
		Object src = e.getSource();
		if (src == fileNew) {
			controller.newFile();
		} else if (src == fileLoad) {
			controller.loadFile();
		} else if (src == fileSaveAs) {
			controller.saveFile();
		} else if (src == fileExit) {
			controller.exit();
		}
	}

	public int confirmDialog(String message) {
		int result = JOptionPane.showConfirmDialog(this, message, "Confirm dialog", JOptionPane.YES_NO_CANCEL_OPTION);
		switch (result) {
			case JOptionPane.YES_OPTION:
				return CONFIRM_YES;
			case JOptionPane.NO_OPTION:
				return CONFIRM_NO;
			default:
				return CONFIRM_CANCEL;
		}
	}

	public void modelUpdated(Model model) {
	}

	public String loadFileDialog() {
		JFileChooser dialog = new JFileChooser();
		if (dialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			return dialog.getSelectedFile().getAbsolutePath();
		} else {
			return null;
		}
	}

	public void exceptionDialog(Exception e) {
		JOptionPane.showMessageDialog(this, e.getMessage(), "Exception dialog", JOptionPane.ERROR_MESSAGE);
	}

	public String saveAsFileDialog() {
		JFileChooser dialog = new JFileChooser();
		if (dialog.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
			return dialog.getSelectedFile().getAbsolutePath();
		} else {
			return null;
		}
	}
}
